package com.glowdayz.glowmee;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.CDialog;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.AddItem;
import com.glowdayz.model.UserInfo;

public class Setup extends Activity implements OnClickListener {
	
	private ActivityManager am = ActivityManager.getInstance();
	
	LinearLayout editPw = null, logOut = null, outRegister = null, version = null;
	TextView eMail = null;
	String url = "";
	
	SharedPreferences prefs = null;      
	SharedPreferences.Editor editor = null;
	
	String lastVersion = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setup);
		
		am.addActivity(this);
		
		Intent fromIntent = getIntent();
		lastVersion = fromIntent.getStringExtra("PARAM_version");
		
		ImageView okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setVisibility(View.GONE);
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		TextView textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText("설정");
		
		editPw = (LinearLayout) findViewById(R.id.editPw);
		logOut = (LinearLayout) findViewById(R.id.logOut);
		outRegister = (LinearLayout) findViewById(R.id.outRegister);
		version = (LinearLayout) findViewById(R.id.version);
		
		editPw.setOnClickListener(this);
		editPw.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent arg1) {
				v.setBackgroundResource(android.R.drawable.list_selector_background);
				return false;
			}
		});
		logOut.setOnClickListener(this);
		logOut.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent arg1) {
				v.setBackgroundResource(android.R.drawable.list_selector_background);
				return false;
			}
		});
		outRegister.setOnClickListener(this);
		outRegister.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent arg1) {
				v.setBackgroundResource(android.R.drawable.list_selector_background);
				return false;
			}
		});
		version.setOnClickListener(this);
		version.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent arg1) {
				v.setBackgroundResource(android.R.drawable.list_selector_background);
				return false;
			}
		});
		
		prefs = getSharedPreferences("Save", MODE_PRIVATE);      
		editor = prefs.edit();
		
		final ToggleButton autoLoginBt = (ToggleButton) findViewById(R.id.autoLoginBt);
		if (UserInfo.getInstance().isAUTO_LOGIN()) {
			autoLoginBt.setChecked(true);
		} else {
			autoLoginBt.setChecked(false);
		}
		autoLoginBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (autoLoginBt.isChecked()) {
					UserInfo.getInstance().setAUTO_LOGIN(true);
					editor.putBoolean("auto", true);
					editor.commit();
				} else {
					UserInfo.getInstance().setAUTO_LOGIN(false);
					editor.putBoolean("auto", false);
					editor.commit();
				}
			}
		});
		
		eMail = (TextView) findViewById(R.id.eMail);
		if (UserInfo.getInstance().getUSER_EMAIL() != null) {
			eMail.setText("(" + UserInfo.getInstance().getUSER_EMAIL().trim() + ")");
		}
		
		final ToggleButton pushAlramBt = (ToggleButton) findViewById(R.id.pushAlramBt);
		if (prefs.getBoolean("push", true)) {
			pushAlramBt.setChecked(true);
		} else {
			pushAlramBt.setChecked(false);
		}
		pushAlramBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (pushAlramBt.isChecked()) {
					editor.putBoolean("push", true);
					editor.commit();
				} else {
					editor.putBoolean("push", false);
					editor.commit();
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.editPw:
			Intent editPw = new Intent(this, EditPassword.class);
			startActivityForResult(editPw, 1);
			break;
		case R.id.logOut:
			AlertDialog.Builder logout = new AlertDialog.Builder(new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog));
			logout.setTitle("로그아웃");
			logout.setMessage("정말 로그아웃 하시겠습니까?");
			logout.setCancelable(false);
			logout.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					SharedPreferences prefs = getSharedPreferences("Save", MODE_PRIVATE);      
					SharedPreferences.Editor editor = prefs.edit();
					editor.putString("eMail", ""); 
					editor.putString("pw", "");
					editor.putBoolean("auto", false);
					editor.commit();
					
					UserInfo.freeInstance();
					
					AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(Setup.this, android.R.style.Theme_Holo_Light_Dialog));
					alert.setTitle("로그아웃 성공");
					alert.setMessage("로그아웃 되었습니다.");
					alert.setCancelable(false);
					alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(Setup.this, MainActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(intent);
						}
					});
					alert.create();
					alert.show();
				}
			});
			logout.setNegativeButton("취소", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
			});
			logout.create();
			logout.show();
			break;
		case R.id.outRegister:
			AlertDialog.Builder confirm = new AlertDialog.Builder(new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog));
			confirm.setTitle("탈퇴");
			confirm.setMessage("정말 탈퇴하시겠습니까?");
			confirm.setCancelable(false);
			confirm.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new OutRegisterWorker()).execute();
				}
			});
			confirm.setNegativeButton("취소", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
			});
			confirm.create();
			confirm.show();
			break;
		case R.id.version:
			PackageInfo pi= null;
			try {
				pi= this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
			
			AlertDialog.Builder check = new AlertDialog.Builder(new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog));
			check.setTitle("버전정보");
			check.setCancelable(false);
			if (pi.versionName.equals(lastVersion)) {
				check.setMessage("최신버전입니다.");
				check.setNegativeButton("닫기", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
			} else {
				check.setMessage("현재버전 : " + pi.versionName + "   /   최신버전 : " + lastVersion);
				check.setPositiveButton("업데이트", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setData(Uri.parse("market://details?id=com.beautytalk.android"));
						startActivity(intent);
					}
				});
				check.setNegativeButton("취소", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
			}
			check.create();
			check.show();
			break;
		}
	}
	
	public class OutRegisterWorker extends AsyncTask<Object, AddItem, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(Setup.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			url = getResources().getString(R.string.server_url) + "/glowmee/outRegisterXml.do?id=" + UserInfo.getInstance().getUSER_ID();
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();
				
				/** 읽은 내용을 담기 위한 변수 */
				String rt = null;
				String rtmsg = null;
				int seq = 0;
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("rt")) {
							parser.next();
							rt = parser.getText();
						} else if (tag.equals("rtmsg")) {
							parser.next();
							rtmsg = parser.getText();
						} else if (tag.equals("seq")) {
							parser.next();
							seq = Integer.parseInt(parser.getText().trim());
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("JSPglowmee")) {
							AddItem item = new AddItem(rt, rtmsg, seq);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(AddItem... param) {
			if (param[0].getRt().equals("SUCCESS")) {
				SharedPreferences prefs = getSharedPreferences("Save", MODE_PRIVATE);      
				SharedPreferences.Editor editor = prefs.edit();
				editor.putString("eMail", ""); 
				editor.putString("pw", "");
				editor.commit();
				
				UserInfo.freeInstance();
				
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(Setup.this, android.R.style.Theme_Holo_Light_Dialog));
				alert.setTitle("탈퇴성공");
				alert.setMessage(param[0].getRtmsg());
				alert.setCancelable(false);
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(Setup.this, MainActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
					}
				});
				alert.create();
				alert.show();
			} else {
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(Setup.this, android.R.style.Theme_Holo_Light_Dialog));
				alert.setTitle("탈퇴실패");
				alert.setMessage(param[0].getRtmsg());
				alert.setCancelable(false);
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				alert.create();
				alert.show();
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}

		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(Setup.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new OutRegisterWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}

}